﻿using System;
using Microsoft.Practices.Unity;
using TestByWire.AttributeHandlers;

namespace TestByWire
{
	[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
	public sealed class UseStubAttribute : Attribute, IContainerInteraction
	{
		public UseStubAttribute(Type interfaceType, Type implementationType)
			: this(interfaceType, implementationType, null)
		{
		}

		public UseStubAttribute(Type interfaceType, Type implementationtype, string instanceName)
		{
			InterfaceType = interfaceType;
			ImplementationType = implementationtype;
			InstanceName = instanceName;
		}

		public Type InterfaceType { get; private set; }
		public Type ImplementationType { get; private set; }
		public string InstanceName { get; private set; }

	    Type IContainerInteraction.RegistrationType
	    {
            get { return InterfaceType; }
	    }

	    string IContainerInteraction.RegistrationName
	    {
	        get { return InstanceName; }
	    }

	    public void Execute(IBuildContext buildContext)
	    {
            if (buildContext.TestTarget != null)
                return;

            IUnityContainer container = buildContext.Container;
            container.RegisterType(InterfaceType, ImplementationType, InstanceName);

            var settings = container.Resolve<PipelineSettings>();
            settings.DoNotStubList.Add(new DoNotStub(InterfaceType, InstanceName));
	    }
	}
}
